<template>
  <div v-loading="loadings" class="app-container">
    <!-- 添加银行卡 -->
    <h5 class="titleInfo">添加银行卡</h5>
    <el-form ref="form" :model="form" :rules="rules" label-width="180px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="银行卡类型">
            <el-select v-model="form.accountType" filterable placeholder="请选择">
              <el-option
                v-for="item in reviewStatusList"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- 对私账户 -->
        <div v-if="form.accountType == 2">
          <el-col :span="24">
            <el-form-item label="银行卡号" prop="cardNo">
              <el-input
                v-model="form.cardNo"
                placeholder="请输入银行卡号"
                @blur="getBankName"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="开户行名称" prop="bankTitle">
              <el-input v-model="form.bankTitle" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="姓名" prop="accountTitle">
              <el-input v-model="form.accountTitle" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="身份证号" prop="identity">
              <el-input v-model="form.identity" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="验证码" prop="code">
              <el-input v-model="form.code" placeholder="请输入验证码" style="width:250px" />
              <el-button
                type="primary"
                :disabled="content.indexOf('s后重新发送')>-1"
                @click="sendmsg(form.phone)"
              >{{ content }}</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="24" />

          <el-col :span="24">
            <el-form-item label="委托书及其附件" prop="attachment">
              <attachment
                ref="uploadImg"
                :file-num="6"
                :file-list="fileList"
                :size-number="4"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label=" ">
              <p class="titlep">
                1、请先下载《委托书模板》
                <a
                  style="color:#409eff"
                  href="http://mpingtest.ameimeika.com/api/commonDownloadFile?fileCode=10001"
                >点击下载</a>
              </p>
              <p
                class="titlep"
              >2、委托书盖章后请上传扫描件，并上传委托书要求的其余附件，最多允许上传6个附件，支持格式：JPG、PNG、JPEG</p>
            </el-form-item>
          </el-col>
        </div>
        <!-- 对公账户 -->
        <div v-else>
          <el-col :span="24">
            <el-form-item label="银行卡号" prop="cardNo">
              <el-input v-model="form.cardNo" placeholder="请输入银行卡号" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="开户行名称" prop="bankTitle">
              <!-- <el-input v-model="form.bankTitle" disabled /> -->
              <el-select v-model="form.bankTitle" filterable placeholder="请选择银行">
                <el-option
                  v-for="(item,index) in bankNameList"
                  :key="index"
                  :label="item.bankName"
                  :value="item.bankName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="开户行支行" prop="branchTitle">
              <el-input v-model="form.branchTitle" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="企业账户名称" prop="accountTitle">
              <el-input v-model="form.accountTitle" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24"></el-col> -->
          <el-col :span="24">
            <el-form-item label="法人姓名" prop="enpUser">
              <el-input v-model="form.enpUser" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="社会信用码" prop="enpCode">
              <el-input v-model="form.enpCode" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label=" ">
              <p class="titlep">
                <span>*</span> 以上信息请核实后填写，若信息错误，将无法绑定银行卡，后期无法进行提现
                <br>成功提交后提示“我们会向贵单位的对公银行账户提交一笔1元以下的打款申请，请在收到款后回填打款金额完成认证即可绑定成功
              </p>
            </el-form-item>
          </el-col>
        </div>
        <el-col :span="24">
          <el-form-item label=" ">
            <el-button type="primary" @click="submitFn('form')">确定</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>
<script>
import attachment from '@/components/imgUpload/uploadimg'
import { getMsg, addCard, getBank, getBankName } from '@/api/financeCard'
import axios from 'axios'

export default {
  name: 'CardAdd',
  components: { attachment },
  data() {
    var attachmentRules = (rule, value, callback) => {
      if (this.form.attachment.length == 0) {
        callback(new Error('请上传委托书及其附件'))
      } else {
        callback()
      }
    }
    var validateNum = (rule, value, callback) => {
      const number = /^(1[3456789]\d{9})$/
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!number.test(value)) {
        callback(new Error('请输入正确电话号码'))
      } else {
        callback()
      }
    }
    // 银行卡
    var cardNum = (rule, value, callback) => {
      const regNum = /^\d{13,19}$/
      if (!value) {
        callback(new Error('请银行卡号'))
      } else if (
        this.form.accountType == 2 &&
                (!regNum.test(value) || !this.cardFlag)
      ) {
        callback(new Error('请输入正确的银行卡号'))
      } else if (this.form.accountType == 1 && !regNum.test(value)) {
        callback(new Error('请输入正确的银行卡号'))
      } else {
        callback()
      }
    }
    // 身份证号验证
    var validateIdentity = (rule, value, callback) => {
      const isIDCard = /(^\d{15}$)|(^\d{17}([0-9]|X)$)/
      if (!value) {
        callback(new Error('请输入身份证号'))
      } else if (!isIDCard.test(value)) {
        callback(new Error('请输入正确身份证号'))
      } else {
        callback()
      }
    }
    var validateBusType = (rule, value, callback) => {
      const Card = /(^(?:(?![IOZSV])[\dA-Z]){2}\d{6}(?:(?![IOZSV])[\dA-Z]){10}$)/
      if (!value) {
        callback(new Error('请输入社会信用代码'))
      } else if (!Card.test(value)) {
        callback(new Error('请输入正确的统一社会信用代码'))
      } else {
        callback()
      }
    }
    return {
      loadings: false,
      hospitalId: null,
      content: '获取验证码',
      totalTime: 60,
      canClick: true, // 添加canClick
      fileList: [],
      cardFlag: false,
      form: {
        accountType: 2,
        bankTitle: ''
      },
      flag: true,
      reviewStatusList: [
        { name: '对公账户', value: 1 },
        { name: '对私账户', value: 2 }
      ],
      bankNameList: [],
      rules: {
        accountTitle: [
          {
            required: true,
            message: '请输入姓名或企业账户名称',
            trigger: 'blur'
          }
        ],
        cardNo: [
          { required: true, validator: cardNum, trigger: 'blur' }
        ],
        phone: [
          { required: true, validator: validateNum, trigger: 'blur' }
        ],
        attachment: [{ required: true, validator: attachmentRules }],
        bankTitle: [
          { required: true, message: '请选择银行', trigger: 'change' }
        ],
        identity: [
          {
            required: true,
            validator: validateIdentity,
            trigger: 'blur'
          }
        ],
        branchTitle: [
          {
            required: true,
            message: '请输入开户行支行',
            trigger: 'blur'
          }
        ],
        enpUser: [
          {
            required: true,
            message: '请输入法人姓名',
            trigger: 'blur'
          }
        ],
        enpCode: [
          {
            required: true,
            validator: validateBusType,
            trigger: 'blur'
          }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    'form.accountType'(e) {
      this.$refs.form.clearValidate()
      this.form = {
        accountType: e,
        bankTitle: ''
      }
    }
  },
  inject: ['reload'],
  mounted() {
    this.getBankList()
  },
  methods: {
    // 银行下拉
    getBankList() {
      getBank().then(res => {
        // console.log(res)
        if (res.data.code == 0) {
          this.bankNameList = res.data.data
        }
      })
    },
    // 银行名称
    getBankName() {
      const regNum = /^\d{13,19}$/
      if (this.form.cardNo && regNum.test(this.form.cardNo)) {
        this.cardFlag = false
        getBankName({ cardNo: this.form.cardNo }).then(res => {
          // console.log(res.data)
          if (res.data.code == 0) {
            this.$nextTick(() => {
              this.form.bankTitle = res.data.data
              this.cardFlag = true
              this.$refs.form.validateField('cardNo')
            })
          } else {
            this.form.bankTitle = ''
            this.cardFlag = false
          }
        })
      }
    },

    // 发送短信
    sendmsg(phone) {
      if (this.form.phone) {
        const datas = {
          phone: this.form.phone,
          type: '1103'
        }
        axios
          .post('http://basicts.ameimeika.com//mmk/msg/send', datas)
          .then(res => {
            if (res.data.code == 200) {
              if (!this.canClick) return
              this.canClick = false
              this.content = this.totalTime + 's后重新发送'
              const clock = window.setInterval(() => {
                this.totalTime--
                this.content = this.totalTime + 's后重新发送'
                if (this.totalTime < 0) {
                  window.clearInterval(clock)
                  this.content = '重新发送验证码'
                  this.totalTime = 60
                  this.canClick = true // 这里重新开启
                }
              }, 1000)
            } else {
              this.errorStatus(res.data.msg)
            }
          })
          .catch(err => {
            this.errorStatus(err)
          })
      } else {
        this.errorStatus('请先填写手机号码后在点击获取验证码')
      }
    },
    addFn() {
      addCard(this.form).then(res => {
        if (res.data.code == 0) {
          this.$message({
            message: '添加成功!',
            type: 'success'
          })
          this.flag = true
          this.reload()
          this.$router.push('cardMange')
        } else if (res.data.code == 8999) {
          this.flag = true
          this.$message({
            message: res.data.msg,
            type: 'warning'
          })
        } else {
          this.flag = true
          this.$message({
            message: res.data.msg,
            type: 'warning'
          })
        }
      })
    },
    // 提交
    submitFn(e) {
      if (this.form.accountType == 2 && this.flag) {
        this.form.attachment = this.$refs.uploadImg.submitUpload()
        const datas = {
          phone: Number(this.form.phone),
          code: Number(this.form.code)
        }

        this.$refs[e].validate(valid => {
          if (valid) {
            if (this.flag) {
              this.flag = false
              axios
                .post(
                  'http://basicts.ameimeika.com//mmk/msg/check_code',
                  datas
                )
                .then(res => {
                  if (res.data.code == 200) {
                    this.form.attachment = this.form.attachment.join(
                      ','
                    )
                    this.addFn()
                  } else {
                    this.$message({
                      message: '验证码错误或已过期',
                      type: 'warning'
                    })
                    this.flag = true
                  }
                })
                .catch(err => {
                  this.flag = true
                  // this.errorStatus(err.msg);
                })
            }
          } else {
            this.$message({
              message: '有必填项没填，不能提交咯',
              type: 'warning'
            })
          }
        })
      }
      if (this.form.accountType == 1) {
        this.$refs[e].validate(valid => {
          if (valid) {
            if (this.flag) {
              this.flag = false
              this.form.identity = this.form.enpCode
              // delete this.form.enpCode
              this.addFn()
            }
          } else {
            this.$message({
              message: '有必填项没填，不能提交咯',
              type: 'warning'
            })
          }
        })
      }
    },
    // 成功状态弹窗
    succStatus(txt, status) {
      this.eleMsg(txt, 'success')
    },
    // 失败状态弹窗
    errorStatus(txt) {
      this.eleMsg(txt, 'error')
    },
    // 弹窗组件
    eleMsg(txt, status) {
      this.$message({
        showClose: true,
        message: txt,
        type: status
      })
    }
  }
}
</script>
<style scoped>
.app-container {
    padding: 0.1px !important;
}
.titlep {
    font-size: 12px;
    color: #606266;
    margin-bottom: 0;
    height: 22px;
    line-height: 22px;
}
.titlep span {
    color: red;
    font-size: 14px;
}
</style>
